package com.seek.seekblog.web.admin;

import com.github.pagehelper.PageInfo;
import com.seek.seekblog.entity.Tag;
import com.seek.seekblog.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/admin")
public class TagController {

    @Autowired
    private TagService tagService;

    @GetMapping("/tags")
    public String tags(HttpServletRequest request, Model model){
        Integer pageNo = request.getParameter("pageNo") == null?1:Integer.valueOf(request.getParameter("pageNo"));
        PageInfo<Tag> pageInfo = tagService.listTags(pageNo,10);
        model.addAttribute("page",pageInfo);
        return "admin/tags";
    }

    @GetMapping("/getTags")
    public String getTags(Model model){
        model.addAttribute("tags",tagService.listTags());
        return "admin/blogs :: tagList";
    }

    @GetMapping("/tags/input")
    public String input(Model model){
        model.addAttribute("tag",new Tag());
        return "admin/tags-input";
    }

    @PostMapping("/tags")
    public String save(Tag tag, RedirectAttributes attributes){
        Tag t = tagService.saveTag(tag,attributes);
        return "redirect:/admin/tags";
    }

    @PostMapping("/tags/{id}")
    public String save(Tag tag, @PathVariable Long id, RedirectAttributes attributes){
        tag.setId(id);
        Tag t = tagService.updateTag(tag,attributes);
        return "redirect:/admin/tags";
    }

    @GetMapping("/tags/{id}/input")
    public String editInput(@PathVariable Long id, Model model){
        model.addAttribute("tag",tagService.getTag(id));
        return "admin/tags-input";
    }

    @GetMapping("/tags/{id}/delete")
    public String delete(@PathVariable Long id, RedirectAttributes attributes){
        tagService.deleteTag(id,attributes);
        return "redirect:/admin/tags";
    }
}
